package be.vsko.zelfevaluatie.rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import be.vsko.zelfevaluatie.framework.Survey;
import be.vsko.zelfevaluatie.help.QueryParameters;
import be.vsko.zelfevaluatie.jackson.mapping.Document;
import be.vsko.zelfevaluatie.jackson.mapping.ExtendedSurvey;
import be.vsko.zelfevaluatie.jackson.mapping.Resource;
import be.vsko.zelfevaluatie.jackson.mapping.SimpleSurvey;
import be.vsko.zelfevaluatie.persistence.DbManager;

@Path("surveys")
public class SurveyServelet extends RoaServlet{
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Document getSurveys(
			@DefaultValue(DEFAULT_LIMIT+"")@QueryParam("limit") int limit,
			@DefaultValue("0")@QueryParam("offset") int offset,
			@DefaultValue("name")@QueryParam("orderby") String orderBy,
			@DefaultValue("false")@QueryParam("descending") boolean descending,
			@DefaultValue("")@QueryParam("modifiedsince") String modifiedSince,
			@DefaultValue("")@QueryParam("name") String name) {
		
		QueryParameters query = new QueryParameters(limit, offset, orderBy, "name", descending);
		query.addFilter("modifiedsince", modifiedSince)
			.addFilter("name", name);
		
		List<Survey> surveys = DbManager.getDb().getSurveys(query);
		
		Document doc = new Document(this);
		doc.setMeta(surveys.size(), query, this);
		
		List<Resource> result = new ArrayList<Resource>();
		for(Survey survey: surveys) {
			result.add(new SimpleSurvey(survey, this));
		}
		
		doc.setResult(result);
		
		return doc;
	}
	
	@GET
	@Path("/{key}")
	@Produces(MediaType.APPLICATION_JSON)
	public ExtendedSurvey getSurvey(@PathParam("key") Long key) {
		Survey survey = DbManager.getDb().getSurvey(key);
		ExtendedSurvey exSurvey = new ExtendedSurvey(survey, this);
		return exSurvey;
	}
}
